package io.feige.rpc.protocol.kryo;
import static org.jboss.netty.buffer.ChannelBuffers.dynamicBuffer;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferOutputStream;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Output;
  
public class ObjectKryoEncoder extends OneToOneEncoder {  
    private static final byte[] LENGTH_PLACEHOLDER = new byte[4];
    @Override  
    protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {  
        ChannelBufferOutputStream bout = new ChannelBufferOutputStream(dynamicBuffer(512, ctx.getChannel().getConfig().getBufferFactory()));  
        bout.write(LENGTH_PLACEHOLDER);
        Output output = new Output(bout);
        Kryo kryo = new Kryo();
        kryo.writeClassAndObject(output, msg);  
        output.flush();  
        output.close();  
          
        ChannelBuffer encoded = bout.buffer();  
        encoded.setInt(0, encoded.writerIndex() - 4);  
        return encoded;  
    }  
}  